package net.j4love.spring.session.example.quickstart;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.security.acl.LastOwnerException;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author He Peng
 * @create 2017-05-22 22:33
 * @update 2017-05-22 22:33
 * @updatedesc : 更新说明
 * @see
 */
@RequestMapping(path = "/spring/session")
@RestController
public class Controller {



    @RequestMapping(path = "/set/{id}" , method = RequestMethod.GET)
    public ResponseEntity<String> set(@PathVariable("id") Long id,
                                                      HttpSession session) {

        session.setAttribute("mark",id + "mark");
        session.setAttribute("ID",id);
        session.setAttribute("date",new Date());
        return ResponseEntity.ok("id : " + id + " set attr success");
    }

    @RequestMapping(path = "/get/{id}" , method = RequestMethod.GET)
    public ResponseEntity<Map<String,Object>> get(@PathVariable("id") Long id,
                                                      HttpSession session) {

        Map<String,Object> rps = new HashMap<>();
        Long attrId = (Long) session.getAttribute("ID");
        if (attrId != null && attrId.longValue() == id) {
            Enumeration<String> attributeNames = session.getAttributeNames();
            while (attributeNames.hasMoreElements()) {
                String attrName = attributeNames.nextElement();
                Object attrVal = session.getAttribute(attrName);
                rps.put(attrName,attrVal);
            }
        }
        return ResponseEntity.ok(rps);
    }
}
